<template>
  <!-- 模板不变，仅确保性别显示用1/0枚举 -->
  <div class="caregiver-elder">
    <div class="header">
      <h2>我照护的长者</h2>
      <p>查看您负责照护的长者信息</p>
    </div>
    <div class="content">
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-select
                v-model="searchForm.name"
                placeholder="搜索长者姓名"
                filterable
                clearable
                @change="handleSearch"
            >
              <el-option
                  v-for="elder in allElders"
                  :key="elder.elderId"
                  :label="elder.name"
                  :value="elder.name"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select
                v-model="searchForm.region"
                placeholder="选择区域"
                clearable
                @change="handleSearch"
            >
              <el-option
                  v-for="r in regionOptions"
                  :key="r"
                  :label="r"
                  :value="r"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>
      <div class="elder-list">
        <el-table
            :data="elderList"
            v-loading="loading"
            style="width: 100%"
            @row-click="handleRowClick"
        >
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="age" label="年龄" width="80" />
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="{ row }">
              {{ row.gender === 1 ? '男' : '女' }} <!-- 统一枚举 -->
            </template>
          </el-table-column>
          <!-- 其他列不变 -->
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click.stop="viewElderDetail(row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 详情对话框不变 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="长者详细信息"
        width="800px"
        :before-close="handleCloseDetail"
    >
      <div v-if="currentElder" class="elder-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="性别">
            {{ currentElder.gender === 1 ? '男' : '女' }} <!-- 统一枚举 -->
          </el-descriptions-item>
          <!-- 其他描述项不变 -->
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { elderApi } from '@/api/elder.js'
import { useUserStore } from '@/store/user' // 新增：获取当前登录用户信息

// 响应式数据不变
const loading = ref(false)
const elderList = ref([])
const currentElder = ref(null)
const detailDialogVisible = ref(false)
const allElders = ref([])
const regionOptions = ref([])
const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 })
const searchForm = reactive({ name: '', region: '' })

// 新增：获取当前护工ID（从用户状态中获取，确保仅查自己负责的老人）
const userStore = useUserStore()
const currentCaregiverId = userStore.userInfo.caregiverId // 假设用户信息中存护工ID

// 修复：加载护工负责的老人（接口传caregiverId过滤）
const fetchElderList = async () => {
  loading.value = true
  try {
    // 护工仅查自己负责的老人：传caregiverId参数
    const response = await elderApi.getElders({
      caregiverId: currentCaregiverId,
      pageNum: 1,
      pageSize: 999
    })
    if (response.code === 200) {
      allElders.value = response.data.records || []
      const regions = [...new Set(allElders.value.map(e => e.elderSector))].sort()
      regionOptions.value = regions
      applyFilter()
    } else {
      ElMessage.error('获取长者列表失败')
    }
  } catch (error) {
    ElMessage.error('获取长者列表失败')
  } finally {
    loading.value = false
  }
}

// 筛选/搜索/分页逻辑不变
const applyFilter = () => {
  let filtered = allElders.value
  if (searchForm.name) filtered = filtered.filter(e => e.name.includes(searchForm.name))
  if (searchForm.region) filtered = filtered.filter(e => e.elderSector === searchForm.region)
  pagination.total = filtered.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  elderList.value = filtered.slice(start, end)
}
const handleSearch = () => { pagination.currentPage = 1; applyFilter() }
const resetSearch = () => { searchForm.name = ''; searchForm.region = ''; pagination.currentPage = 1; applyFilter() }
const handleSizeChange = (size) => { pagination.pageSize = size; pagination.currentPage = 1; applyFilter() }
const handleCurrentChange = (page) => { pagination.currentPage = page; applyFilter() }
const handleRowClick = (row) => { viewElderDetail(row) }
const viewElderDetail = (elder) => { currentElder.value = elder; detailDialogVisible.value = true }
const handleCloseDetail = () => { detailDialogVisible.value = false; currentElder.value = null }

// 初始化加载
onMounted(() => {
  fetchElderList()
})
</script>
<style scoped>
/* 样式不变 */
</style>